package com.gitee.wsl.text

class RelativeCharSequence(
    val input: CharSequence,
    val fromIndex: Int = 0,
    val toIndex: Int = input.length
) : CharSequence {

    init {
        require(fromIndex in input.indices) { "fromIndex must be less than or equal to toIndex" }
        require(toIndex <= input.length) { "toIndex must be less than or equal to input.length" }
    }

    private fun checkIndex(index: Int): Int {
        require(index in 0 until length) { "index must be in range [0, length)" }
        return index
    }

    override val length: Int get() = toIndex - fromIndex

    override fun get(index: Int): Char {
        checkIndex(index)
        return input[index + fromIndex]
    }

    override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
        checkIndex(startIndex)
        checkIndex(endIndex)
        return input.subSequence(startIndex + fromIndex, endIndex + fromIndex)
    }

    override fun toString(): String = subSequence(0, length) as String
}

fun CharSequence.getRelativeCharSequence(start: Int, end: Int = length) = RelativeCharSequence(this, start)
